from flask import Flask, render_template, request, jsonify, redirect, url_for, session, send_from_directory, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_required, login_user, logout_user, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime, timedelta
import os
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False 
app.config['SECRET_KEY'] = 'your-secret-key-here'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:xxxxxxxx@192.168.1.1:3306/xxxxxx_db?charset=utf8mb4'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB

db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

# 创建上传文件夹
if not os.path.exists(app.config['UPLOAD_FOLDER']):
    os.makedirs(app.config['UPLOAD_FOLDER'])

# 模型定义
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(255), unique=True, nullable=False)
    password_hash = db.Column(db.String(500), nullable=False)
    
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
        
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

class Carousel(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    image_url = db.Column(db.String(200))
    link_url = db.Column(db.String(200))
    sort_order = db.Column(db.Integer, default=0)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text)
    image_url = db.Column(db.String(200))
    sort_order = db.Column(db.Integer, default=0)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

class About(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text, nullable=False)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

class News(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
    summary = db.Column(db.Text)
    image_url = db.Column(db.String(200))
    publish_date = db.Column(db.DateTime, default=datetime.utcnow)
    sort_order = db.Column(db.Integer, default=0)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

class Case(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text)
    image_url = db.Column(db.String(200))
    link_url = db.Column(db.String(200))
    sort_order = db.Column(db.Integer, default=0)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

class Job(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    department = db.Column(db.String(50))
    location = db.Column(db.String(50))
    requirements = db.Column(db.Text)
    responsibilities = db.Column(db.Text)
    sort_order = db.Column(db.Integer, default=0)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

class Message(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    is_read = db.Column(db.Boolean, default=False)

# 用户认证相关
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = User.query.filter_by(username=username).first()
        
        if user and user.check_password(password):
            login_user(user)
            return redirect(url_for('admin_dashboard'))
        else:
            return render_template('login.html', error='用户名或密码错误')
    
    return render_template('login.html')

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('index'))

@app.route('/admin/about/delete', methods=['POST'])
@login_required
def admin_about_delete():
    about = About.query.first()
    if about:
        db.session.delete(about)
        db.session.commit()
    return redirect(url_for('admin_dashboard'))

# 前端页面路由
@app.route('/')
def index():
    carousels = Carousel.query.order_by(Carousel.sort_order.asc()).all()
    products = Product.query.order_by(Product.sort_order.asc()).limit(6).all()
    news_list = News.query.order_by(News.publish_date.desc()).limit(3).all()
    cases = Case.query.order_by(Case.sort_order.asc()).limit(4).all()
    about = About.query.first()  # 获取 about 数据
    return render_template('index.html', carousels=carousels, products=products, news=news_list, cases=cases, about=about)

@app.route('/products')
def products():
    products = Product.query.order_by(Product.sort_order.asc()).all()
    return render_template('products.html', products=products)

@app.route('/about')
def about():
    about = About.query.first()
    return render_template('about.html', about=about)

@app.route('/news')
def news():
    page = request.args.get('page', 1, type=int)
    per_page = 10
    # 修改 paginate 调用方式，使用关键字参数
    pagination = News.query.order_by(News.publish_date.desc()).paginate(page=page, per_page=per_page, error_out=False)
    news_list = pagination.items
    return render_template('news.html', news=news_list, pagination=pagination)

@app.route('/news/<int:id>')
def news_detail(id):
    news_item = News.query.get_or_404(id)
    return render_template('news_detail.html', news=news_item)

@app.route('/jobs')
def jobs():
    jobs = Job.query.order_by(Job.sort_order.asc()).all()
    return render_template('jobs.html', jobs=jobs)

@app.route('/cases')
def cases():
    cases = Case.query.order_by(Case.sort_order.asc()).all()
    return render_template('cases.html', cases=cases)

@app.route('/contact')
def contact():
    return render_template('contact.html')

@app.route('/message', methods=['POST'])  # 留言提交路由
def submit_message():
    data = request.get_json()
    if not data:
        return jsonify({'status': 'error', 'message': '请求数据格式必须为 JSON'}), 400

    name = data.get('name')
    email = data.get('email')
    content = data.get('content')

    if not all([name, email, content]):
        return jsonify({'status': 'error', 'message': '请填写所有必填字段'}), 400

    message = Message(name=name, email=email, content=content)
    try:
        db.session.add(message)
        db.session.commit()
        return jsonify({'status': 'success', 'message': '留言提交成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 'error', 'message': str(e)}), 500

# 管理后台路由
@app.route('/admin')
@login_required
def admin_dashboard():
    return render_template('admin/dashboard.html')

# 文件上传辅助函数
def upload_file(file):
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(file_path)
        return f'/uploads/{filename}'
    return None

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'doc', 'docx'}

# 轮播图管理API
@app.route('/api/carousels', methods=['GET'])
@login_required
def get_carousels():
    carousels = Carousel.query.order_by(Carousel.sort_order.asc()).all()
    return jsonify([{
        'id': carousel.id,
        'title': carousel.title,
        'image_url': carousel.image_url,
        'link_url': carousel.link_url,
        'sort_order': carousel.sort_order
    } for carousel in carousels])

@app.route('/api/carousels', methods=['POST'])
@login_required
def create_carousel():
    title = request.form.get('title')
    link_url = request.form.get('link_url')
    sort_order = request.form.get('sort_order', 0, type=int)
    
    file = request.files.get('image')
    image_url = upload_file(file) if file else None
    
    carousel = Carousel(
        title=title,
        image_url=image_url,
        link_url=link_url,
        sort_order=sort_order
    )
    
    db.session.add(carousel)
    db.session.commit()
    
    return jsonify({
        'id': carousel.id,
        'title': carousel.title,
        'image_url': carousel.image_url,
        'link_url': carousel.link_url,
        'sort_order': carousel.sort_order
    }), 201

@app.route('/api/carousels/<int:id>', methods=['DELETE','GET'])
@login_required
def delete_carousel(id):
    carousel = Carousel.query.get_or_404(id)
    db.session.delete(carousel)
    db.session.commit()
    carousels = Carousel.query.order_by(Carousel.sort_order.asc()).all()
    return render_template('admin/carousels.html', carousels=carousels)

# 产品管理API
@app.route('/api/products', methods=['GET'])
@login_required
def get_products():
    products = Product.query.order_by(Product.sort_order.asc()).all()
    return jsonify([{
        'id': product.id,
        'name': product.name,
        'description': product.description,
        'image_url': product.image_url,
        'sort_order': product.sort_order
    } for product in products])

@app.route('/api/products', methods=['POST'])
@login_required
def create_product():
    name = request.form.get('name')
    description = request.form.get('description')
    sort_order = request.form.get('sort_order', 0, type=int)
    
    file = request.files.get('image')
    image_url = upload_file(file) if file else None
    
    product = Product(
        name=name,
        description=description,
        image_url=image_url,
        sort_order=sort_order
    )
    
    db.session.add(product)
    db.session.commit()
    
    return jsonify({
        'id': product.id,
        'name': product.name,
        'description': product.description,
        'image_url': product.image_url,
        'sort_order': product.sort_order
    }), 201
@app.route('/api/products/<int:id>', methods=['GET'])
@login_required
def get_product(id):
    product = Product.query.get_or_404(id)
    if request.args.get('edit') == 'true':
        # 渲染 add.html 模板并传递产品信息
        return render_template('admin/news/products/add.html', product=product)
    return jsonify({'error': 'Invalid request'}), 400
    
@app.route('/api/products/<int:id>', methods=['PUT', 'POST'])
@login_required
def update_product(id):
    product = Product.query.get_or_404(id)
    
    name = request.form.get('name')
    description = request.form.get('description')
    sort_order = request.form.get('sort_order', type=int)
    
    file = request.files.get('image')
    if file:
        # 删除旧文件
        if product.image_url:
            old_file_path = os.path.join(app.config['UPLOAD_FOLDER'], os.path.basename(product.image_url))
            if os.path.exists(old_file_path):
                os.remove(old_file_path)
        
        image_url = upload_file(file)
        if image_url:
            product.image_url = image_url
    
    if name is not None:
        product.name = name
    if description is not None:
        product.description = description
    if sort_order is not None:
        product.sort_order = sort_order
    
    db.session.commit()
    
    return jsonify({
        'id': product.id,
        'name': product.name,
        'description': product.description,
        'image_url': product.image_url,
        'sort_order': product.sort_order
    })

@app.route('/api/products/<int:id>', methods=['DELETE'])
@login_required
def delete_product(id):
    product = Product.query.get_or_404(id)
    
    # 删除关联文件
    if product.image_url:
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], os.path.basename(product.image_url))
        if os.path.exists(file_path):
            os.remove(file_path)
    
    db.session.delete(product)
    db.session.commit()
    return jsonify({'status': 'success'})

# 关于我们管理API
@app.route('/api/about', methods=['GET'])
@login_required
def get_about():
    about = About.query.first() or About(content='')
    return jsonify({
        'id': about.id,
        'content': about.content
    })

@app.route('/api/about', methods=['PUT'])
@login_required
def update_about():
    content = request.json.get('content')
    
    about = About.query.first()
    if not about:
        about = About(content=content)
        db.session.add(about)
    else:
        about.content = content
    
    db.session.commit()
    
    return jsonify({
        'id': about.id,
        'content': about.content
    })

# 新闻管理API
@app.route('/api/news', methods=['GET'])
@login_required
def get_news():
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    news_query = News.query.order_by(News.publish_date.desc())
    
    if 'keyword' in request.args:
        keyword = request.args['keyword']
        news_query = news_query.filter(News.title.contains(keyword) | News.content.contains(keyword))
    
    pagination = news_query.paginate(page, per_page=per_page, error_out=False)
    news_list = pagination.items
    
    return jsonify({
        'items': [{
            'id': news.id,
            'title': news.title,
            'content': news.content,
            'summary': news.summary,
            'image_url': news.image_url,
            'publish_date': news.publish_date.isoformat(),
            'sort_order': news.sort_order
        } for news in news_list],
        'total': pagination.total,
        'pages': pagination.pages,
        'page': pagination.page,
        'per_page': pagination.per_page
    })

@app.route('/api/news', methods=['POST'])
@login_required
def create_news():
    title = request.form.get('title')
    content = request.form.get('content')
    summary = request.form.get('summary')
    publish_date = request.form.get('publish_date') or datetime.utcnow()
    sort_order = request.form.get('sort_order', 0, type=int)
    
    if isinstance(publish_date, str):
        publish_date = datetime.fromisoformat(publish_date)
    
    file = request.files.get('image')
    image_url = upload_file(file) if file else None
    
    news = News(
        title=title,
        content=content,
        summary=summary,
        image_url=image_url,
        publish_date=publish_date,
        sort_order=sort_order
    )
    
    db.session.add(news)
    db.session.commit()
    
    return jsonify({
        'id': news.id,
        'title': news.title,
        'content': news.content,
        'summary': news.summary,
        'image_url': news.image_url,
        'publish_date': news.publish_date.isoformat(),
        'sort_order': news.sort_order
    }), 201

@app.route('/api/news/<int:id>', methods=['PUT'])
@login_required
def update_news(id):
    news = News.query.get_or_404(id)
    
    title = request.form.get('title')
    content = request.form.get('content')
    summary = request.form.get('summary')
    publish_date = request.form.get('publish_date')
    sort_order = request.form.get('sort_order', type=int)
    
    if publish_date:
        news.publish_date = datetime.fromisoformat(publish_date)
    
    file = request.files.get('image')
    if file:
        image_url = upload_file(file)
        if image_url:
            news.image_url = image_url
    
    if title is not None:
        news.title = title
    if content is not None:
        news.content = content
    if summary is not None:
        news.summary = summary
    if sort_order is not None:
        news.sort_order = sort_order
    
    db.session.commit()
    
    return jsonify({
        'id': news.id,
        'title': news.title,
        'content': news.content,
        'summary': news.summary,
        'image_url': news.image_url,
        'publish_date': news.publish_date.isoformat(),
        'sort_order': news.sort_order
    })

@app.route('/api/news/<int:id>', methods=['DELETE'])
@login_required
def delete_news(id):
    news = News.query.get_or_404(id)
    db.session.delete(news)
    db.session.commit()
    return jsonify({'status': 'success'})

# 案例管理API
@app.route('/api/cases', methods=['GET'])
@login_required
def get_cases():
    cases = Case.query.order_by(Case.sort_order.asc()).all()
    return jsonify([{
        'id': case.id,
        'title': case.title,
        'description': case.description,
        'image_url': case.image_url,
        'link_url': case.link_url,
        'sort_order': case.sort_order
    } for case in cases])

@app.route('/api/cases', methods=['POST'])
@login_required
def create_case():
    title = request.form.get('title')
    description = request.form.get('description')
    link_url = request.form.get('link_url')
    sort_order = request.form.get('sort_order', 0, type=int)
    
    file = request.files.get('image')
    image_url = upload_file(file) if file else None
    
    case = Case(
        title=title,
        description=description,
        image_url=image_url,
        link_url=link_url,
        sort_order=sort_order
    )
    
    db.session.add(case)
    db.session.commit()
    
    return jsonify({
        'id': case.id,
        'title': case.title,
        'description': case.description,
        'image_url': case.image_url,
        'link_url': case.link_url,
        'sort_order': case.sort_order
    }), 201

@app.route('/api/cases/<int:id>', methods=['PUT'])
@login_required
def update_case(id):
    case = Case.query.get_or_404(id)
    
    title = request.form.get('title')
    description = request.form.get('description')
    link_url = request.form.get('link_url')
    sort_order = request.form.get('sort_order', type=int)
    
    file = request.files.get('image')
    if file:
        image_url = upload_file(file)
        if image_url:
            case.image_url = image_url
    
    if title is not None:
        case.title = title
    if description is not None:
        case.description = description
    if link_url is not None:
        case.link_url = link_url
    if sort_order is not None:
        case.sort_order = sort_order
    
    db.session.commit()
    
    return jsonify({
        'id': case.id,
        'title': case.title,
        'description': case.description,
        'image_url': case.image_url,
        'link_url': case.link_url,
        'sort_order': case.sort_order
    })

@app.route('/api/cases/<int:id>', methods=['DELETE'])
@login_required
def delete_case(id):
    case = Case.query.get_or_404(id)
    db.session.delete(case)
    db.session.commit()
    return jsonify({'status': 'success'})

# 招聘管理API
@app.route('/api/jobs', methods=['GET'])
@login_required
def get_jobs():
    jobs = Job.query.order_by(Job.sort_order.asc()).all()
    return jsonify([{
        'id': job.id,
        'title': job.title,
        'department': job.department,
        'location': job.location,
        'requirements': job.requirements,
        'responsibilities': job.responsibilities,
        'sort_order': job.sort_order
    } for job in jobs])

@app.route('/api/jobs', methods=['POST'])
@login_required
def create_job():
    title = request.form.get('title')
    department = request.form.get('department')
    location = request.form.get('location')
    requirements = request.form.get('requirements')
    responsibilities = request.form.get('responsibilities')
    sort_order = request.form.get('sort_order', 0, type=int)
    
    job = Job(
        title=title,
        department=department,
        location=location,
        requirements=requirements,
        responsibilities=responsibilities,
        sort_order=sort_order
    )
    
    db.session.add(job)
    db.session.commit()
    
    return jsonify({
        'id': job.id,
        'title': job.title,
        'department': job.department,
        'location': job.location,
        'requirements': job.requirements,
        'responsibilities': job.responsibilities,
        'sort_order': job.sort_order
    }), 201

@app.route('/api/jobs/<int:id>', methods=['PUT'])
@login_required
def update_job(id):
    job = Job.query.get_or_404(id)
    
    title = request.form.get('title')
    department = request.form.get('department')
    location = request.form.get('location')
    requirements = request.form.get('requirements')
    responsibilities = request.form.get('responsibilities')
    sort_order = request.form.get('sort_order', type=int)
    
    if title is not None:
        job.title = title
    if department is not None:
        job.department = department
    if location is not None:
        job.location = location
    if requirements is not None:
        job.requirements = requirements
    if responsibilities is not None:
        job.responsibilities = responsibilities
    if sort_order is not None:
        job.sort_order = sort_order
    
    db.session.commit()
    
    return jsonify({
        'id': job.id,
        'title': job.title,
        'department': job.department,
        'location': job.location,
        'requirements': job.requirements,
        'responsibilities': job.responsibilities,
        'sort_order': job.sort_order
    })

@app.route('/api/jobs/<int:id>', methods=['DELETE'])
@login_required
def delete_job(id):
    job = Job.query.get_or_404(id)
    db.session.delete(job)
    db.session.commit()
    return jsonify({'status': 'success'})

# 留言管理API
@app.route('/api/messages', methods=['GET'])
@login_required
def get_messages():
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    messages = Message.query.order_by(Message.created_at.desc()).paginate(page, per_page=per_page, error_out=False)
    
    return jsonify({
        'items': [{
            'id': message.id,
            'name': message.name,
            'email': message.email,
            'content': message.content,
            'created_at': message.created_at.isoformat(),
            'is_read': message.is_read
        } for message in messages.items],
        'total': messages.total,
        'pages': messages.pages,
        'page': messages.page,
        'per_page': messages.per_page
    })

@app.route('/api/messages/<int:id>/read', methods=['PUT'])
@login_required
def mark_message_read(id):
    message = Message.query.get_or_404(id)
    message.is_read = True
    db.session.commit()
    return jsonify({'status': 'success'})

# 新闻列表
@app.route('/admin/news/list')
@login_required
def admin_news_list():
    page = request.args.get('page', 1, type=int)
    per_page = 10
    pagination = News.query.order_by(News.publish_date.desc()).paginate(page=page, per_page=per_page, error_out=False)
    news_list = pagination.items
    return render_template('admin/news/list.html', news_list=news_list, pagination=pagination)

@app.route('/admin/news/delete/<int:id>', methods=['GET', 'POST'])
@login_required
def admin_news_delete(id):
    news = News.query.get_or_404(id)
    db.session.delete(news)
    db.session.commit()
    return redirect(url_for('admin_news_list'))

# 新闻编辑和添加路由
@app.route('/admin/news/edit', defaults={'id': None}, methods=['GET', 'POST'])
@app.route('/admin/news/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def admin_news_edit(id):
    if request.method == 'POST':
        title = request.form.get('title')
        content = request.form.get('content')
        summary = request.form.get('summary')
        
        if id:
            # 编辑现有新闻
            news = News.query.get_or_404(id)
            news.title = title
            news.content = content
            news.summary = summary
        else:
            # 添加新新闻
            news = News(
                title=title,
                content=content,
                summary=summary
            )
            db.session.add(news)
        
        db.session.commit()
        return redirect(url_for('admin_news_list'))
    
    if id:
        news = News.query.get_or_404(id)
        return render_template('admin/news/edit.html', news=news)
    else:
        return render_template('admin/news/edit.html')

# 产品列表
@app.route('/admin/products/list')
@login_required
def admin_products_list():
    products = Product.query.all()
    return render_template('admin/news/products/list.html', products=products)

# 添加产品
@app.route('/admin/products/add', methods=['GET', 'POST'])
@login_required
def admin_products_add():
    if request.method == 'POST':
        name = request.form['name']
        description = request.form['description']
        image = request.files.get('image')
        image_url = upload_file(image) if image else None
        
        product = Product(name=name, description=description, image_url=image_url)
        db.session.add(product)
        db.session.commit()
        return redirect(url_for('admin_products_list'))
    return render_template('admin/news/products/add.html')

@app.route('/admin/products/categories')
@login_required
def admin_products_categories():
    # 这里可根据需求扩展分类管理逻辑
    return render_template('admin/news/products/categories.html')

# 案例管理
@app.route('/admin/cases/list')
@login_required
def admin_cases_list():
    cases = Case.query.all()
    return render_template('admin/news/cases/list.html', cases=cases)

@app.route('/admin/cases/add', methods=['GET', 'POST'])
@login_required
def admin_cases_add():
    if request.method == 'POST':
        title = request.form['title']
        description = request.form['description']
        image = request.files.get('image')
        image_url = upload_file(image) if image else None
        link_url = request.form.get('link_url')
        
        case = Case(title=title, description=description, image_url=image_url, link_url=link_url)
        db.session.add(case)
        db.session.commit()
        return redirect(url_for('admin_cases_list'))
    return render_template('admin/news/cases/add.html')

# 关于我们管理
@app.route('/admin/about', methods=['GET', 'POST'])
@login_required
def admin_about():
    about = About.query.first()
    if not about:
        about = About(content='')
        db.session.add(about)
        db.session.commit()
    
    if request.method == 'POST':
        about.content = request.form['content']
        db.session.commit()
        return jsonify({'success': True, 'message': '保存成功'})
    return render_template('admin/about.html', about=about)

@app.route('/admin/jobs')
@login_required
def admin_jobs():
    return redirect(url_for('admin_jobs_list'))

# 招聘管理
@app.route('/admin/jobs/list')
@login_required
def admin_jobs_list():
    jobs = Job.query.all()
    return render_template('admin/news/jobs/list.html', jobs=jobs)

@app.route('/admin/jobs/add', methods=['GET', 'POST'])
@login_required
def admin_jobs_add():
    if request.method == 'POST':
        title = request.form['title']
        department = request.form['department']
        location = request.form['location']
        requirements = request.form['requirements']
        responsibilities = request.form['responsibilities']
        
        job = Job(
            title=title,
            department=department,
            location=location,
            requirements=requirements,
            responsibilities=responsibilities
        )
        db.session.add(job)
        db.session.commit()
        return redirect(url_for('admin_jobs_list'))
    return render_template('admin/news/jobs/add.html')

# 留言管理
@app.route('/admin/messages')
@login_required
def admin_messages():
    messages = Message.query.all()
    return render_template('admin/messages.html', messages=messages)

@app.route('/admin/messages/detail/<int:id>')
@login_required
def admin_messages_detail(id):
    message = Message.query.get_or_404(id)
    return render_template('admin/messages/detail.html', message=message)


@app.route('/admin/users')
@login_required
# 渲染用户管理页面
def admin_users():
    return render_template('admin/users.html')

@app.route('/admin/users/list', methods=['GET'])
@login_required
# 获取用户列表
def admin_users_list():
    users = User.query.all()
    user_list = [{"id": user.id, "username": user.username} for user in users]
    return jsonify(user_list)
@app.route('/admin/users/<int:id>', methods=['GET'])
@login_required
# 获取单个用户信息
def get_user(id):
    user = User.query.get_or_404(id)
    return jsonify({
        'id': user.id,
        'username': user.username
    })

@app.route('/admin/users/<int:id>', methods=['PUT'])
@login_required
# 更新用户信息
def update_user(id):
    user = User.query.get_or_404(id)
    data = request.get_json()
    if not data:
        return jsonify({'success': False, 'message': '未提供有效数据'}), 400
    
    if 'username' in data:
        user.username = data['username']
    
    try:
        db.session.commit()
        return jsonify({'success': True, 'message': '用户信息更新成功', 'user': {
            'id': user.id,
            'username': user.username
        }})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': str(e)}), 500

@app.route('/admin/users/<int:id>', methods=['DELETE'])
@login_required
def delete_user(id):
    user = User.query.get_or_404(id)
    db.session.delete(user)
    db.session.commit()
    return jsonify({'message': 'User deleted successfully'}), 200

# 网站设置接口
@app.route('/admin/settings', methods=['GET'])
@login_required
# 修改此路由以渲染设置页面
def get_settings():
    # 渲染设置页面
    return render_template('admin/settings.html')

@app.route('/admin/settings', methods=['POST'])
@login_required
def update_settings():
    data = request.get_json()
    # 这里可以将设置保存到数据库或配置文件中
    # 示例返回成功消息
    return jsonify({'message': 'Settings updated successfully'}), 200

@app.route('/admin/messages/<int:id>', methods=['DELETE'])
@login_required
def delete_message(id):
    message = Message.query.get_or_404(id)
    db.session.delete(message)
    db.session.commit()
    return jsonify({'status': 'success'})




@app.route('/admin/products/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def admin_products_edit():
    if request.method == 'POST':
        name = request.form['name']
        description = request.form['description']
        product = Product(name=name, description=description)
        db.session.add(product)
        db.session.commit()
        return redirect(url_for('admin_products_list'))
    return render_template('admin/products/edit.html')

@app.route('/admin/jobs/edit/<int:id>', methods=['GET', 'POST'])  # 修改为支持 POST 请求
@login_required
def admin_jobs_edit(id):
    job = Job.query.get_or_404(id)
    if request.method == 'POST':
        try:
            job.title = request.form.get('title')
            job.department = request.form.get('department')
            job.location = request.form.get('location')
            job.requirements = request.form.get('requirements')
            job.responsibilities = request.form.get('responsibilities')
            job.sort_order = request.form.get('sort_order')
            
            db.session.commit()
            flash('职位信息更新成功', 'success')
            return redirect(url_for('admin_jobs_list'))
        except Exception as e:
            db.session.rollback()
            flash('更新失败: ' + str(e), 'error')
            return redirect(url_for('admin_jobs_edit', id=id))
    return render_template('admin/news/jobs/edit.html', job=job)

# @app.route('/admin/jobs/edit/<int:id>', methods=['GET'])
# @login_required
# def admin_jobs_edit(id):
#     job = Job.query.get_or_404(id)
#     # 这里可以渲染编辑页面模板
#     return render_template('admin/news/jobs/edit.html', job=job)

@app.route('/admin/jobs/delete/<int:id>', methods=['GET', 'POST'])
@login_required
def admin_jobs_delete(id):
    job = Job.query.get_or_404(id)
    try:
        db.session.delete(job)
        db.session.commit()
        return redirect(url_for('admin_jobs_list'))
    except Exception as e:
        db.session.rollback()
        flash('删除失败: ' + str(e), 'error')
        return redirect(url_for('admin_jobs_list'))

@app.route('/admin/messages/list', methods=['GET'])
@login_required
def admin_messages_list():
    # 从数据库获取所有留言
    messages = Message.query.all()
    message_list = [{
        'id': msg.id,
        'name': msg.name,
        'email': msg.email,
        'content': msg.content
    } for msg in messages]
    return jsonify(message_list)

@app.route('/admin/messages/delete/<int:id>', methods=['DELETE'])
@login_required
def admin_messages_delete(id):
    try:
        message = Message.query.get_or_404(id)
        db.session.delete(message)
        db.session.commit()
        return jsonify({'success': True, 'message': '删除成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': str(e)}), 500
# 配置上传文件的静态文件路由
@app.route('/uploads/<path:filename>')
def uploads(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

@app.route('/api/stats', methods=['GET'])
def get_stats():
    # 获取新闻总数
    news_count = News.query.count()
    
    # 获取上月新闻总数
    last_month = datetime.utcnow() - timedelta(days=30)
    last_month_news_count = News.query.filter(News.created_at >= last_month).count()
    news_percentage = ((news_count - last_month_news_count) / last_month_news_count * 100) if last_month_news_count else 0
    
    # 获取产品总数
    product_count = Product.query.count()
    last_month_product_count = Product.query.filter(Product.created_at >= last_month).count()
    product_percentage = ((product_count - last_month_product_count) / last_month_product_count * 100) if last_month_product_count else 0
    
    # 获取案例总数
    case_count = Case.query.count()
    last_month_case_count = Case.query.filter(Case.created_at >= last_month).count()
    case_percentage = ((case_count - last_month_case_count) / last_month_case_count * 100) if last_month_case_count else 0
    
    # 获取留言总数
    message_count = Message.query.count()
    last_month_message_count = Message.query.filter(Message.created_at >= last_month).count()
    message_percentage = ((message_count - last_month_message_count) / last_month_message_count * 100) if last_month_message_count else 0
    
    # 获取最近新闻
    recent_news = News.query.order_by(News.publish_date.desc()).limit(5).all()
    recent_news_data = [{
        'title': news.title,
        'content': news.content,  # 假设存在 category 字段，若不存在需调整
        'publish_date': news.publish_date.strftime('%Y-%m-%d'),
        'summary': news.summary,
        'image_url': news.image_url,
        'created_at': news.created_at
    } for news in recent_news]
    
    # 获取最近留言
    recent_messages = Message.query.order_by(Message.created_at.desc()).limit(5).all()
    recent_messages_data = [{
        'name': message.name,
        'content': message.content,
        'created_at': message.created_at.strftime('%Y-%m-%d')
    } for message in recent_messages]
    
    return jsonify({
        'news': {
            'count': news_count,
            'percentage': round(news_percentage, 2)
        },
        'products': {
            'count': product_count,
            'percentage': round(product_percentage, 2)
        },
        'cases': {
            'count': case_count,
            'percentage': round(case_percentage, 2)
        },
        'messages': {
            'count': message_count,
            'percentage': round(message_percentage, 2)
        },
        'recent_news': recent_news_data,
        'recent_messages': recent_messages_data
    })

@app.route('/api/carousels/<int:id>', methods=['PUT'])
@login_required
def update_carousel(id):
    carousel = Carousel.query.get_or_404(id)
    
    title = request.form.get('title')
    link_url = request.form.get('link_url')
    sort_order = request.form.get('sort_order', type=int)
    
    file = request.files.get('image')
    if file:
        image_url = upload_file(file)
        if image_url:
            carousel.image_url = image_url
    
    if title is not None:
        carousel.title = title
    if link_url is not None:
        carousel.link_url = link_url
    if sort_order is not None:
        carousel.sort_order = sort_order
    
    db.session.commit()
    
    return jsonify({
        'id': carousel.id,
        'title': carousel.title,
        'image_url': carousel.image_url,
        'link_url': carousel.link_url,
        'sort_order': carousel.sort_order
    })



@app.route('/admin/carousels')
@login_required
def admin_carousels():
      carousels = Carousel.query.order_by(Carousel.sort_order.asc()).all()
      return render_template('admin/carousels.html', carousels=carousels)

@app.route('/admin/carousel/edit', defaults={'id': None}, methods=['GET', 'POST'])
@app.route('/admin/carousel/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def admin_carousel_edit(id):
      if id:
          carousel = Carousel.query.get_or_404(id)
      else:
          carousel = None

      if request.method == 'POST':
          title = request.form.get('title')
          link_url = request.form.get('link_url')
          sort_order = request.form.get('sort_order', type=int)

          file = request.files.get('image')
          if file:
              image_url = upload_file(file)
              if image_url:
                  if carousel:
                      carousel.image_url = image_url
                  else:
                      image_url = image_url

          if carousel:
              carousel.title = title
              carousel.link_url = link_url
              carousel.sort_order = sort_order
          else:
              carousel = Carousel(
                  title=title,
                  image_url=image_url,
                  link_url=link_url,
                  sort_order=sort_order
              )
              db.session.add(carousel)

          db.session.commit()
          return redirect(url_for('admin_carousels'))

      return render_template('admin/carousel_edit.html', carousel=carousel)

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
        # 创建管理员账户（仅首次运行时需要）
        if not User.query.first():
            admin = User(username='admin')
            admin.set_password('admin123456789')
            db.session.add(admin)
            db.session.commit()
    app.run(debug=True)